package com.yc.cloud.mapper;

import com.yc.cloud.entity.HwDeviceCamera;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备摄像头关联表 Mapper 接口
 * </p>
 *
 * @author kinggu
 * @since 2025-08-27
 */
@Mapper
public interface HwDeviceCameraMapper extends BaseMapper<HwDeviceCamera> {

    /**
     * 根据设备ID查询绑定的摄像头ID列表
     * @param deviceId 设备ID
     * @return 摄像头ID列表
     */
    default List<Long> selectCameraIdsByDeviceId(Long deviceId) {
        return this.selectList(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.DeviceId, deviceId)
        ).stream().map(HwDeviceCamera::getCameraId).collect(Collectors.toList());
    }

    /**
     * 根据摄像头ID查询绑定的设备ID
     * 反向查询：从摄像头找到设备
     * @param cameraId 摄像头ID
     * @return 设备ID，如果未找到返回null
     */
    default Long selectDeviceIdByCameraId(Long cameraId) {
        if (cameraId == null) {
            return null;
        }
        HwDeviceCamera deviceCamera = this.selectOne(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.CameraId, cameraId)
                .last("LIMIT 1") // 通常一个摄像头只绑定一个设备
        );
        return deviceCamera != null ? deviceCamera.getDeviceId() : null;
    }

    /**
     * 检查设备和摄像头是否已绑定
     * @param deviceId 设备ID
     * @param cameraId 摄像头ID
     * @return 是否已绑定
     */
    default boolean existsBinding(Long deviceId, Long cameraId) {
        return this.selectCount(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.DeviceId, deviceId)
                .eq(HwDeviceCamera.CameraId, cameraId)
        ) > 0;
    }

    /**
     * 解绑指定的摄像头
     * @param deviceId 设备ID
     * @param cameraIds 摄像头ID列表
     * @return 删除成功的记录数
     */
    default int unbindCameras(Long deviceId, List<Long> cameraIds) {
        return this.delete(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.DeviceId, deviceId)
                .in(HwDeviceCamera.CameraId, cameraIds)
        );
    }

    /**
     * 解绑设备下的所有摄像头
     * @param deviceId 设备ID
     * @return 删除成功的记录数
     */
    default int unbindAllCamerasByDevice(Long deviceId) {
        return this.delete(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.DeviceId, deviceId)
        );
    }

    /**
     * 清理指定摄像头与设备的绑定关系（用于绑定前清理）
     * 删除已存在的绑定记录，为后续重新绑定做准备
     * @param deviceId 设备ID
     * @param cameraIds 摄像头ID列表
     * @return 删除成功的记录数
     */
    default int clearExistingBindings(Long deviceId, List<Long> cameraIds) {
        return this.delete(
            new QueryWrapper<HwDeviceCamera>()
                .eq(HwDeviceCamera.DeviceId, deviceId)
                .in(HwDeviceCamera.CameraId, cameraIds)
        );
    }


} 